<template>
  <!--  -->
  <!-- 文件分享窗口 -->
  <!--  -->
  <div>
    <Dialog
      :show="dialogConfig.show"
      :title="dialogConfig.title"
      :buttons="dialogConfig.buttons"
      :showCancel="showCancel"
      width="600px"
      @close="dialogConfig.show = false">

          <!-- 表单 -->
        <el-form :model="formData" :rules="rules" ref="formDataRef" label-width="100px" @submit.prevent>

            <!-- 文件名 -->
            <el-form-item label="文件" prop="">
                {{ formData.fileName }}
            </el-form-item>

            <!-- 完成分享前展示内容 -->
            <template v-if="showType == 0">
                <!-- 有效期选择 -->
                <el-form-item label="有效期" prop="validType">
                    <el-radio-group v-model="formData.validType">  <!-- 双向绑定 -->
                    <el-radio :label="0">1天</el-radio>
                    <el-radio :label="1">7天</el-radio>
                    <el-radio :label="2">30天</el-radio>
                    <el-radio :label="3">永久有效</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- 提取码生成 -->
                <el-form-item label="提取码" prop="codeType">
                    <el-radio-group v-model="formData.codeType">  <!-- 双向绑定 -->
                    <el-radio :label="0">自定义</el-radio>
                    <el-radio :label="1">系统生成</el-radio>
                    </el-radio-group>
                </el-form-item>
                <!-- 提取码输入框 -->
                <el-form-item prop="code" v-if="formData.codeType == 0">
                    <el-input 
                    clearable 
                    placeholder="请输入5位数提取码" 
                    v-model="formData.code"
                    maxlength="5"
                    :style="{ width: '120px' }">
                    </el-input>
                </el-form-item>
            </template>

            <!-- 完成分享后展示内容 -->
            <template v-else>
                <!-- 分享链接 -->
                <el-form-item label="分享链接">
                    {{ shareUrl }}{{ resultInfo.shareId }}
                </el-form-item>
                <!-- 提取码 -->
                <el-form-item label="提取码">
                    {{ resultInfo.code }}
                </el-form-item>
                <!-- 复制按钮 -->
                <el-form-item>
                    <el-button type="primary" @click="copy">复制链接及提取码</el-button>
                </el-form-item>
            </template>
        </el-form>
      </Dialog>
  </div>
</template>

<script setup>
import useClipboard from "vue-clipboard3";     //读取剪切板内容，依赖下载在package.json第27行
const { toClipboard } = useClipboard();        //往剪切板写入
import { ref, reactive, getCurrentInstance, nextTick, onMounted, computed } from "vue";
const { proxy } = getCurrentInstance();

const api = {
    shareFile: "/share/shareFile",
};

const rules = {    //根据form表单中的prop属性进行选择校验（proxy.Verify已在main.js中声明）
    validType: [{ required: true, message:"请选择有效期" }],
    codeType: [{ required: true, message:"请选择提取码类型" }],
    code:  [             
        { required: true, message:"请输入提取码" },
        { validator: proxy.Verify.shareCode, message:"格式错误" },
        { min: 5, message:"提取码最少为5位数" },
    ],
};

const shareUrl = ref(document.location.origin + "/share/"); //分享链接（后面需加上shareId）
const showType = ref(0);                                    //用于区分是否已完成分享。0:分享前 1:分享后

const formData = ref({});    //表单
const formDataRef = ref();   //对象，用于校验
const resultInfo = ref({});  //分享完成后的返回值（包含code）

//弹窗的属性
const showCancel = ref(true);    //是否展示多一个“取消”按钮
const dialogConfig = ref({
    show: false,   //false为关闭弹窗
    title: "分享",
    buttons: [
        {
          type: "primary",
          text: "确定",
          click: (e) => {
            share();    //确定按钮
          },
        },
    ],
});


/**
 * 打开弹窗。由Main.vue的share方法调用
 */
const show = (data) => {
    showType.value = 0;             //用于区分是否已完成分享。0:分享前 1:分享后
    showCancel.value = true;        //展示“取消”按钮
    dialogConfig.value.show = true; //打开弹窗
    resultInfo.value = {};          //分享之后的返回值

    nextTick(() => {
        //初始化表单对象
        formDataRef.value.resetFields();
        formData.value = Object.assign({}, data);  
    })
};
defineExpose({ show });   //是Vue3中的一个新特性,它允许组件将其内部的数据和方法暴露给父组件


/**
 * 弹窗 “确定/关闭” 按钮
 */
const share = async () => {
    if (Object.keys(resultInfo.value).length > 0) {   //resultInfo的值数量大于0时
        dialogConfig.value.show = false;
        return;
    }
    formDataRef.value.validate(async (valid) => {
        if (!valid) { return; }  //校验不通过，则直接返回
        let params = {};
        Object.assign(params, formData.value);
        let result = await proxy.Request({
            url: api.shareFile,
            params: params,
        });
        if (!result) {
            return;
        };
        showType.value = 1;                   //用于区分是否已完成分享。0:分享前 1:分享后
        resultInfo.value = result.data.share; //分享之后的返回值（包含code）
        dialogConfig.value.buttons[0].text = "关闭" //将“确定”按钮修改为“关闭”
        showCancel.value = false;             //隐藏“取消”按钮
    });
};


/**
 * 复制按钮
 */
const copy = async () => {
    //将内容往剪切板中写入
    await toClipboard(`链接:${shareUrl.value}${resultInfo.value.shareId} 提取码:${resultInfo.value.code}`); 
    proxy.Message.success("复制成功");
}

</script>

<style>

</style>